/*
 * 文件名： WechatWcPay.java
 * 
 * 工程名称: bis-service
 *
 * Gopay
 *
 * 创建日期： 2016年10月10日
 *
 * Copyright(C) 2016, by www.gopay.com.cn Inc.All rights reserved.
 *
 * 原始作者: 宣广海
 *
 */
package com.gopay.bis.service.bank.impl.wcpay;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;

import com.gopay.bis.common.util.BankLogUtils;
import com.gopay.bis.manager.bank.wcpay.WechatWcpayCiticManager;
import com.gopay.common.Result;
import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.domain.bank.BaseMessage;
import com.gopay.common.domain.bank.wechat.wcpay.citic.req.WcPayQueryReqMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.req.WcPayReqMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.req.WcRefundQueryReqMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.req.WcRefundReqMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayNotifyMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayQueryResMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcPayResMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcRefundItem;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcRefundQueryResMsg;
import com.gopay.common.domain.bank.wechat.wcpay.citic.res.WcRefundResMsg;
import com.gopay.common.exception.GopayException;
import com.gopay.common.util.TransUtil;
import com.gopay.remote.bank.WcPayInteractRemoteService;

/**
 * 
 *
 * @author 宣广海
 *
 * @version
 *
 * @since 2016年10月10日
 */
public class WechatWcPayCiticServiceImpl implements WcPayInteractRemoteService {
	private static Logger logger = LoggerFactory.getLogger(WechatWcPayCiticServiceImpl.class);
	@Resource(name = "wechatWcpayCiticManager")
	private WechatWcpayCiticManager wechatWcpayCiticManager;

	@Override
	public Result pay(BaseMessage msg) throws GopayException {
		/**
		 * 定义返回对象
		 */
		Result result = new Result(false);
		try {
			WcPayReqMsg message = new WcPayReqMsg();
			BeanUtils.copyProperties(msg, message);
			WcPayResMsg resMessage = (WcPayResMsg) wechatWcpayCiticManager.sign(message);
			msg.setBankOrderId(message.getBankOrderId());
			if (resMessage != null) {
				if ("0".equals(resMessage.getStatus())) {
					if ("0".equals(resMessage.getResult_code())) {
						resMessage.setPayInfo(resMessage.getPay_info());
						result.setDefaultModel(resMessage); // 收银台从wcPayBaseMessage
											
						result.setSuccess(true);
					} else {
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E1159);
						result.setErrorMsg(resMessage.getErr_msg());
						result.setSuccess(false);
					}
				} else {
					result.setSuccess(false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E7028);
					result.setErrorMsg(resMessage.getMessage());
				}
			} else {
				result.setSuccess(false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E7025);
			}
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E7025);
		}
		return result;

	}

	@Override
	public Result orderQuery(BaseMessage msg) throws GopayException {
	    Result result = new Result();
	    try{	        
	        WcPayQueryReqMsg message = new WcPayQueryReqMsg();
	        BeanUtils.copyProperties(msg,message);
	        WcPayQueryResMsg resMsg =(WcPayQueryResMsg)wechatWcpayCiticManager.orderQuery(message);	        
	        if(("".equals(resMsg.getTotal_fee()))||(resMsg.getTotal_fee() == null)){
	            resMsg.setAmount(message.getAmount());
	        }else{
	            resMsg.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(resMsg.getTotal_fee())));
	        }	        
	        result.setDefaultModel(resMsg);
	        result.setSuccess(true);
	    } catch (GopayException e) {
            BankLogUtils.printServiceImplExceptionLog(e);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
        } catch (Exception ex) {
            BankLogUtils.printServiceImplExceptionLog(ex);
            result.setResultCode(ProcCodeConstants.PROC_CODE_100E7027);
        }
        return result;
	}

	@Override
	public Result refund(BaseMessage msg) throws GopayException {

		Result result = new Result(false);
		try {
			WcRefundReqMsg message = new WcRefundReqMsg();
			BeanUtils.copyProperties(msg, message);
			WcRefundResMsg resMsg = (WcRefundResMsg) wechatWcpayCiticManager.refund(message);

			if (resMsg != null) {
				if ("0".equals(resMsg.getStatus())) {
					if ("0".equals(resMsg.getResult_code())) {
						result.setDefaultModel(resMsg);
						result.setSuccess(true);
						// 接收成功
						result.setModel("falg", true);
					} else {
						result.setResultCode(ProcCodeConstants.PROC_CODE_100E6088);
						result.setErrorMsg(resMsg.getErr_msg());
						result.setModel("falg", false);
						result.setSuccess(true);
					}
				} else {
					result.setSuccess(false);
					result.setModel("falg", false);
					result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
					result.setErrorMsg(resMsg.getMessage());
				}
			} else {
				result.setSuccess(false);
				result.setModel("falg", false);
				result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6087);
		}
		return result;

	
	}

	@Override
	public Result refundQuery(BaseMessage msg) throws GopayException {

		Result result = new Result(false);
		WcRefundQueryReqMsg message = new WcRefundQueryReqMsg();
		BeanUtils.copyProperties(msg, message);
		try {
			WcRefundQueryResMsg res = (WcRefundQueryResMsg) wechatWcpayCiticManager.refundQuery(message);			
			if ("0".equals(res.getStatus())){
				if ("0".equals(res.getResult_code())){
					int refundCount = res.getRefund_count();
					for (int i = 0; i < refundCount; i++) {
						WcRefundItem refundItem = res.getRefundItems().get(i);
						logger.error("威富通返回退款订单号为：" + refundItem.getOut_refund_no());
						if (refundItem.getOut_refund_no().equals(message.getBankOrderId())){
							res.setAmount(new BigDecimal(TransUtil.amountConvert2Yuan(refundItem.getRefund_fee())));// 退款金额
						}
					}
				}
			}
			result.setDefaultModel(res);
			result.setSuccess(true);
		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6033);
		}
		return result;
	
	}

	@Override
	public Result verify(BaseMessage msg) throws GopayException {
		Result result = new Result(false);
		try {
			WcPayNotifyMsg message = (WcPayNotifyMsg) msg;
			Boolean flag = (Boolean) wechatWcpayCiticManager.verify(message);
			result.setDefaultModel(flag);
			result.setSuccess(true);
			result.setModel("res", message);
			Map<String, String> param = new HashMap<String, String>(9);
			/**
			 * 验签成功
			 */
			if ((boolean) result.getDefaultModel()) {
				if (("0".equals(message.getPay_result()))) {
					param.put("orderId", message.getOrderId());
					param.put("amt", TransUtil.amountConvert2Yuan(message.getTotal_fee()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "00");
					param.put("retCode", "00");
					param.put("retMsg", "验签成功");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(true);
				} else {
					param.put("orderId", message.getOrderId());
					param.put("amt", TransUtil.amountConvert2Yuan(message.getTotal_fee()));
					param.put("cardType", "Unknown");
					param.put("notifyNum", "1");
					param.put("payStatus", "01");
					param.put("retCode", "01");
					param.put("retMsg", "验签失败");
					param.put("signData", "");
					param.put("isFront", String.valueOf(message.isFront()));
					result.setModel("isNotifyCashier", param);
					result.setOrderStatus(false);
				}
			}

		} catch (GopayException e) {
			BankLogUtils.printServiceImplExceptionLog(e);
			result.setResultCode(e.getErrCode());
		} catch (Exception ex) {
			BankLogUtils.printServiceImplExceptionLog(ex);
			result.setResultCode(ProcCodeConstants.PROC_CODE_100E6064);
		}
		return result;
	}

}
